import React, {Component} from 'react';
import {reqUserList} from '../../api/user';
import {Card, Table, Image, message} from "antd";
import moment from "moment";

// 首页
export default class Users extends Component {
  state = {
    list: [],
    totalCount: 0
  }
  initColumns = () => {
    this.columns = [
      {
        title: '用户名',
        dataIndex: 'nickName',
      },
      {
        title: '头像',
        dataIndex: 'avatarUrl',
        render: (avatarUrl) => <Image src={avatarUrl} width={50}/>
      },
      {
        title: '性别',
        dataIndex: 'gender',
        render: (gender) => {
          if (gender === 0) {
            return '未知';
          } else if (gender === 1) {
            return '男';
          } else {
            return '女';
          }
        }
      },
      {
        title: '注册日期',
        dataIndex: 'add_time',
        align: 'center',
        render: (text) => moment(text).format('YYYY-MM-DD HH:mm:ss')
      },
      {
        title: '角色',
        dataIndex: 'role',
      },
      {
        title: '最后一次登录',
        dataIndex: 'last_time',
        align: 'center',
        render: (text) => moment(text).format('YYYY-MM-DD HH:mm:ss')
      }
    ]
  }

  UNSAFE_componentWillMount() {
    this.initColumns();
  }

  getUserList = async (data={}) => {
    try {
      const {data: result} = await reqUserList(data);
      this.setState({list: result.items, totalCount: result.total_count})
    } catch (e) {
      message.error(e.data.name || e.data.message);
    }
  }

  componentDidMount() {
    this.getUserList();
  }

  onChange = (pagination, filters, sorter, extra) => {
    const {current, pageSize} = pagination;
    const listQuery = Object.assign({},{page: current, page_size: pageSize});
    this.getUserList(listQuery);
  }

  render() {
    const {list, totalCount} = this.state;
    const pagination = {
      defaultPageSize: 10,
      position: ['bottomCenter'],
      showQuickJumper: true,
      total: totalCount,
    }
    return (
      <Card title='用户列表'>
        <Table
          dataSource={list}
          columns={this.columns}
          rowKey='avatarUrl'
          onChange={this.onChange}
          scroll={{x: 800}}
          pagination={pagination}
        />
      </Card>
    )
  }
}
